/*
 * GUISala.java
 *
 * Created on 9 de Setembro de 2007, 20:36
 */

package codebreaker.cliente.sala.gui;

import codebreaker.cliente.Main;
import codebreaker.cliente.jogo.gui.GUIEscolher;
import codebreaker.cliente.sala.Sala;
import codebreaker.cliente.sala.SalaListener;
import codebreaker.commom.Jogador;
import codebreaker.protocolo.ChatPublicoToCliente;
import codebreaker.protocolo.Convite;
import codebreaker.protocolo.RespostaConvite;
import java.net.InetAddress;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author  rodrigo
 */
public class GUISala extends javax.swing.JFrame implements SalaListener {
    
    private boolean convidando = false;
    
    private DefaultListModel listModel;
    
    /** Creates new form GUISala */
    public GUISala(InetAddress endereco, int porta) {
	
	initComponents();
	
	this.setTitle(Main.jogador.getNome() + " - Code Breaker Game Room");
	
	/* conecta-se */
	Main.sala = new Sala(endereco, porta, Main.jogador);
	Main.sala.setSalaListener(this);
	
	/* seta lista de onlines */
	listModel = new DefaultListModel();
	listOnline.setModel(listModel);
	listOnline.setCellRenderer(new ListOnlineRender());
	
	/* adiciona um elemento a conexao */
	listModel.addElement(Main.jogador);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Código Gerado ">//GEN-BEGIN:initComponents
    private void initComponents() {
        panelOnline = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listOnline = new javax.swing.JList();
        btnConvidar = new javax.swing.JButton();
        panelChat = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        textChat = new javax.swing.JTextArea();
        btnEnviar = new javax.swing.JButton();
        textEnviar = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Code Breaker - Game Room");
        setResizable(false);
        panelOnline.setBorder(javax.swing.BorderFactory.createTitledBorder("Jogadores online"));
        jScrollPane1.setViewportView(listOnline);

        btnConvidar.setText("Convidar");
        btnConvidar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConvidarActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout panelOnlineLayout = new org.jdesktop.layout.GroupLayout(panelOnline);
        panelOnline.setLayout(panelOnlineLayout);
        panelOnlineLayout.setHorizontalGroup(
            panelOnlineLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelOnlineLayout.createSequentialGroup()
                .addContainerGap()
                .add(panelOnlineLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                    .add(btnConvidar))
                .addContainerGap())
        );
        panelOnlineLayout.setVerticalGroup(
            panelOnlineLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelOnlineLayout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 364, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(btnConvidar)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panelChat.setBorder(javax.swing.BorderFactory.createTitledBorder("Chat"));
        jScrollPane2.setViewportView(textChat);

        btnEnviar.setText("Enviar");
        btnEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEnviarActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout panelChatLayout = new org.jdesktop.layout.GroupLayout(panelChat);
        panelChat.setLayout(panelChatLayout);
        panelChatLayout.setHorizontalGroup(
            panelChatLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, panelChatLayout.createSequentialGroup()
                .addContainerGap()
                .add(panelChatLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
                    .add(panelChatLayout.createSequentialGroup()
                        .add(textEnviar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnEnviar)))
                .addContainerGap())
        );
        panelChatLayout.setVerticalGroup(
            panelChatLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelChatLayout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 361, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(panelChatLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnEnviar)
                    .add(textEnviar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(panelOnline, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(panelChat, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, panelOnline, 0, 441, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, panelChat, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void btnConvidarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConvidarActionPerformed
	/* verifica jogador a qual o convite eh direcionado */
	
	if (convidando) {
	    JOptionPane.showMessageDialog(this,
		    "Voce esta aguardando a resposta de um convite.",
		    "Aguarde a resposta de outro convite",
		    JOptionPane.ERROR_MESSAGE);
	} else if (listOnline.getSelectedIndex() == -1) {
	    JOptionPane.showMessageDialog(this,
		    "Selecione um jogador da lista.",
		    "Jogador não especificado",
		    JOptionPane.ERROR_MESSAGE);
	} else {
	    Jogador convidado = (Jogador) listOnline.getSelectedValue();
	    
	    if (convidado.equals(Main.jogador)) {
		JOptionPane.showMessageDialog(this,
			"Voce nao pode convidar a si mesmo.",
			"Jogador invalido",
			JOptionPane.ERROR_MESSAGE);
	    } else {
		/* envia convite para jogador */
		Main.sala.enviar(new Convite(convidado.getId()));
		convidando = true;
		JOptionPane.showMessageDialog(this,
			"Convidando " + convidado.getNome() + " para uma partida",
			"Convite",
			JOptionPane.INFORMATION_MESSAGE);
	    }
	}
    }//GEN-LAST:event_btnConvidarActionPerformed
    
    private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnviarActionPerformed
	Main.sala.enviarChatPublico(textEnviar.getText());
	textChat.append(Main.jogador.getNome() + ": " + textEnviar.getText() + "\n");
	textEnviar.setText("");
    }//GEN-LAST:event_btnEnviarActionPerformed
    
    public void recebeuChat(ChatPublicoToCliente chat) {
	textChat.append(Main.sala.getNome(chat.getIdJogador()) + ": " + chat.getTexto() + "\n");
    }
    
    public void recebeuConvite(Convite convite) {
	
	String nome = Main.sala.getNome(convite.getIdJogador());
	
	int resultado = JOptionPane.showConfirmDialog(this,
		nome + " esta lhe convidando para uma partida, aceita o convite?",
		"Convite", JOptionPane.YES_NO_OPTION);
	
	if (resultado == JOptionPane.YES_OPTION) {
	    Main.sala.enviar(new RespostaConvite(convite.getIdJogador(), RespostaConvite.ACEITOU));
	    
	    /* inicia jogo */
	    Main.guiEscolher = new GUIEscolher(nome);
	    Main.guiEscolher.setVisible(true);
	    this.setVisible(false);
	} else {
	    Main.sala.enviar(new RespostaConvite(convite.getIdJogador(), RespostaConvite.DECLINOU));
	}
    }
    
    public void recebeuRespostaConvite(RespostaConvite resposta) {
	
	String nome = Main.sala.getNome(resposta.getIdJogador());
	
	if (resposta.getResposta() == RespostaConvite.ACEITOU) {
	    JOptionPane.showMessageDialog(this,
		    nome + " aceitou seu convite para jogar",
		    "Convite aceito",
		    JOptionPane.INFORMATION_MESSAGE);
	    
	    /* inicia jogo */
	    Main.guiEscolher = new GUIEscolher(nome);
	    Main.guiEscolher.setVisible(true);
	    this.setVisible(false);
	} else {
	    JOptionPane.showMessageDialog(this,
		    nome + " declinou seu convite para jogar",
		    "Convite nao aceito",
		    JOptionPane.INFORMATION_MESSAGE);
	}
	convidando = false;
    }
    
    
    public void conexao(Jogador jogador) {
	textChat.append(jogador.getNome() + " se conectou...\n");
	listModel.addElement(jogador);
    }
    
    public void desconexao(Jogador jogador) {
	textChat.append(jogador.getNome() + " saiu...\n");
	listModel.removeElement(jogador);
    }
    
    public void mudouEstado(Jogador jogador) {
	//listOnline.repaint();
    }
    
    
    // Declaração de variáveis - não modifique//GEN-BEGIN:variables
    private javax.swing.JButton btnConvidar;
    private javax.swing.JButton btnEnviar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList listOnline;
    private javax.swing.JPanel panelChat;
    private javax.swing.JPanel panelOnline;
    private javax.swing.JTextArea textChat;
    private javax.swing.JTextField textEnviar;
    // Fim da declaração de variáveis//GEN-END:variables
    
}
